<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/8/11
 * Time: 15:14
 */

namespace app\api\controller;


use Alipay\aop\AopClient;
use Alipay\aop\request\AlipayTradeWapPayRequest;
use app\service\NotifyService;
use Payment\Client;
use phpmailer\BaseException;
use think\Controller;
use think\Db;
use think\Exception;

class AlipayService extends Controller
{
    /*
    *  @context 支付宝支付
    *  $out_trade_no  商户网站唯一订单号
  * $money  订单金额
  * $body  交易信息
    * */
  public  function JsAliPay($body,$out_trade_no,$money){

          $receive_phone=Db::name('member_order')->where('order_number='.$out_trade_no)->value('receive_phone');
          if($receive_phone=='13080745917')
          {
              $money='0.01';
          }
        #查询 支付宝公钥 支付宝私钥 支付宝appid

        $alipay = Db::table("payapi")->where("type = 2")->find();

        if(!empty($alipay)){
            require_once '../extend/Alipay/AopSdk.php';
            $url =__MY_PUBLIC_URL__.'/api/AlipayService/AlipayCallback';
//            $url ='http://124.70.177.101:6001//api/AlipayService/AlipayCallback';
            $aop = new AopClient();
            #正式网关
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
            $aop->appId = $alipay['appid'];//appid
            $aop->rsaPrivateKey = $alipay['zpkey'];//支付宝私钥
            $aop->format = "json";
            $aop->charset = "UTF-8";
            #商城生成的签名字符串 推荐RSA2   目前使用RSA2 RSA
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $alipay['ppkey'];//请填写支付宝公钥，一行字符串
            //可设置AES密钥，调用AES加解密相关接口时需要（可选）
            $aop->encryptKey = "9D2GNIAnv2a4ycqmrHgl/A==";//<-- 请填写您的AES密钥，例如：aa4BtZ4tspm2wnXLb1ThQA== -->
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            $request = new \AlipayTradeAppPayRequest();
            $data['body'] = '云盟商桥-购买商品'; //对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
            $data['subject']=$body;//商品的标题/交易标题/订单标题/订单关键字等。
            $data['out_trade_no'] = $out_trade_no;//商户网站唯一订单号
            $data['timeout_express'] = '60m'; //该笔订单允许的最晚付款时间，逾期将关闭交易
            $data['total_amount'] = $money; //订单总金额，单位为元
            $data['product_code'] = 'QUICK_MSECURITY_PAY'; //销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
            $bizcontent = json_encode($data);
            $request->setNotifyUrl($url);
             $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
            return $response;//就是orderString 可以直接给客户端请求，无需再做处理。

        }else{
            return false;
        }

    }
    /*
    *  @context 支付宝回调
    *  $out_trade_no  商户网站唯一订单号
  * $money  订单金额
* */
    function AlipayCallback(){
        $info = input("post.");

        if(empty($info))
            exit('fail');
        #查询订单支付状态
        $orderstatus=Db::table("orderspay")->where(array("order_number"=>$info['out_trade_no']))->find();
        #查询订单的状态是否是待付款的状态  为空不执行
        $order = Db::table('member_order')->field('id')->where(array('order_number'=>$info['out_trade_no'],'order_status'=>1))->find();

        if(!empty($order)){
            #证明有这个订单
            if(!empty($orderstatus)){
                if($orderstatus['status']==1){

                  return 'success';
                }else{

                    # 返回接受成功
                    Db::table("orderspay")->where(array("order_number"=>$info['out_trade_no']))->update(array("status"=>1));
                    #修改对应的订单的订单状态  修改对应订单的支付价格

                    #调支付成功方法
                    $WxpayService = new WxpayService();

                    $WxpayService->paySuccess($info['out_trade_no'],$order['id'],$info['total_amount'],2);

                    return 'success';


                }
            }
        }else{
            exit('fail');
        }

    }

    public function Alicallback(){
        $alipay = Db::table("payapi")->where("type = 2")->find();

        $config = [
            'use_sandbox' => true,
            'app_id'    => '2021001187619640',
            'sign_type' => 'RSA2',
            // 支付宝公钥字符串
            'ali_public_key' =>$alipay['ppkey'],
            // 自己生成的密钥字符串
            'rsa_private_key' => $alipay['zpkey'],
            'limit_pay' => [],

            // 与业务相关参数
            'notify_url' => 'http://124.70.177.101:6001/api/AlipayService/AliCallback',
            'return_url' => 'https://dayutalk.cn',
        ];

// 实例化继承了接口的类
        $callback = new NotifyService();

        try {
            $client = new \Payment\Client(\Payment\Client::ALIPAY, $config);
            $xml = $client->notify($callback);
        } catch (\InvalidArgumentException $e) {

            throw new BaseException(['code'=>403 ,'errorCode'=>1014,'msg'=>$e->getMessage(),'status'=>false,'debug'=>false ]);

        } catch (\Payment\Exceptions\GatewayException $e) {
            throw new BaseException(['code'=>403 ,'errorCode'=>1014,'msg'=>$e->getMessage(),'status'=>false,'debug'=>false ]);
        } catch (\Payment\Exceptions\ClassNotFoundException $e) {
            throw new BaseException(['code'=>403 ,'errorCode'=>1014,'msg'=>$e->getMessage(),'status'=>false,'debug'=>false ]);
        } catch (Exception $e) {
            throw new BaseException(['code'=>403 ,'errorCode'=>1014,'msg'=>$e->getMessage(),'status'=>false,'debug'=>false ]);
        }
    }
    function demo(){
        $alipay = Db::table("payapi")->where("type = 2")->find();

        $config = [
            'use_sandbox' => true,
            'app_id'    => '2021001187619640',
            'sign_type' => 'RSA2',
            // 支付宝公钥字符串
            'ali_public_key' =>$alipay['ppkey'],
            // 自己生成的密钥字符串
            'rsa_private_key' => $alipay['zpkey'],
            'limit_pay' => [],

            // 与业务相关参数
            'notify_url' => 'http://124.70.177.101:6001/api/AlipayService/AliCallback',
            'return_url' => 'https://dayutalk.cn',
        ];


        $payData = [
            'body'         => '对一笔交易的具体描述信息。',
            'subject'      => '大乐透',
            'trade_no'     => '70501111111S001111119',// 自己实现生成
            'time_expire'  => time() + 600, // 表示必须 600s 内付款
            'amount'       => '5.52', // 微信沙箱模式，需要金额固定为3.01
            'return_param' => '123',
            'client_ip'    => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1', // 客户地址
        ];
        try {

            $client = new  \Payment\Client('Alipay', $config);

            $res    = $client->pay($client::ALI_CHANNEL_APP, $payData);
        } catch (\InvalidArgumentException $e) {

            throw new BaseException(['code'=>403 ,'errorCode'=>1013,'msg'=>$e->getMessage(),'status'=>false,'debug'=>false ]);


        } catch (\Payment\Exceptions\GatewayException $e) {

            throw new BaseException(['code'=>403 ,'errorCode'=>1013,'msg'=>$e->getMessage(),'status'=>false,'debug'=>false ]);

        } catch (\Payment\Exceptions\ClassNotFoundException $e) {
            throw new BaseException(['code'=>403 ,'errorCode'=>1013,'msg'=>$e->getMessage(),'status'=>false,'debug'=>false ]);

        } catch (Exception $e) {

            throw new BaseException(['code'=>403 ,'errorCode'=>1013,'msg'=>$e->getMessage(),'status'=>false,'debug'=>false ]);
        }

    }
    function wxdemo(){
        return $this->fetch("/alipay/wxpay");
    }

}